package util

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
)

type city struct {
	Pro  string `json:"pro"`
	City string `json:"city"`
	Addr string `json:"addr"`
	Err  string `json:"err"`
}

// IPCity 获取ip所属城市
func IPCity(ip string) string {
	url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
	recv, err := http.Get(url)
	if err != nil {
		return ""
	}
	defer recv.Body.Close()
	data, err := ioutil.ReadAll(recv.Body)
	if err != nil {
		return ""
	}
	var v city
	json.Unmarshal([]byte(ToUTF8(data)), &v)
	if v.Err == "" {
		return v.Pro + v.City
	}
	return v.Addr
}
